<?php

namespace app\common\model\cms;

use app\common\model\BaseModel;

class TableModel extends BaseModel
{

  protected $table = 'cms_table';

  /**
   * 刷新缓存
   * @param $tableName
   * @param bool $refresh
   * @return array|mixed
   * @throws \Exception
   */
  public function getInfo($tableName, $refresh = false)
  {
    $cacheKey = "cms_table_{$tableName}";
    if (cache("?{$cacheKey}") && $refresh == false) return cache($cacheKey);
    $tableInfo = $this->field(true)->where('table_name', $tableName)->find()->toArray();
    $fields    = FieldModel::where('table_name', $tableName)->order('show_order asc')->select()->toArray();
    foreach ($fields as $k => $v) {
      $fields[$k]['obj_options'] = json_decode($v['obj_options'], true);
    }
    $tableInfo['fields'] = $fields;
    cache($cacheKey, $tableInfo);
    return $tableInfo;
  }

  /**
   * 添加表
   * @param $data
   * @return TableModel|\think\Model
   * @throws \Exception
   */
  public function add($data)
  {
    $db   = $this->db();
    $info = null;
    if ($this->where('table_name', $data['table_name'])->find()) exception('已存在对应表名');
    $db->startTrans();
    try {
      //保存模型信息
      $info = self::create($data);
      //生成模型表
      $initSql = str_replace(['@table_name@', '@table_comment@'], [$data['table_name'], $data['display_name']], $this->initSql());
      $db->execute($initSql);
      //初始化字段值
      $this->initField($data['table_name']);
      $this->getInfo($data['table_name'], true);
      $db->commit();
    } catch (\Exception $e) {
      $db->rollback();
      abort(500, $e->getMessage());
    }
    return $info;
  }

  /**
   * 修改模型
   * @param $data
   * @return TableModel
   * @throws \Exception
   */
  public function edit($data)
  {
    $tableName = $data['table_name'];
    if (isset($data['table_name'])) unset($data['table_name']);
    $info = self::update($data);
    $this->getInfo($tableName, true);
    return $info;
  }

  /**
   * 删除模型
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    if ($id == 1) abort(500, '系统内置模型不允许删除');
    $info = $this->where('id', $id)->find();
    if (ClassModel::where('table_name', $info['table_name'])->find()) abort(500, '已有使用分类，不允许删除');
    $db = $this->db();
    $db->startTrans();
    try {
      //删除字段信息
      FieldModel::where('table_name', $info['table_name'])->delete();
      //删除对应表
      $db->execute("DROP TABLE cms_detail_{$info['table_name']}");
      //删除模型信息
      $this->where('id', $id)->delete();
      //删除对应缓存
      cache("cms_table_{$info['table_name']}", null);
      $db->commit();
    } catch (\Exception $e) {
      $db->rollback();
      abort(500, $e->getMessage());
    }
    return true;
  }

  /**
   * 初始化sql
   * @return mixed
   */
  public function initSql()
  {
    return <<<EOT
CREATE TABLE `cms_detail_@table_name@` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `table_name` varchar(30) NOT NULL DEFAULT '' COMMENT '模型表名',
  `uid` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '录入人ID',
  `class_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '栏目ID',
  `title` varchar(255) NOT NULL DEFAULT '' COMMENT '标题',
  `jump` varchar(255) NOT NULL DEFAULT '' COMMENT '跳转URL',
  `views` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '点击数',
  `create_time` int(10) NOT NULL DEFAULT '0' COMMENT '创建时间',
  `update_time` int(10) NOT NULL DEFAULT '0' COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `class_id` (`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='@table_comment@';
EOT;
  }

  /**
   * 初始化字段配置
   * @param $tableName
   * @throws \Exception
   */
  public function initField($tableName)
  {
    $fieldModel = new FieldModel();
    $dataList   = [
        [
            'table_name' => $tableName,
            'label_name' => '栏目分类',
            'field_name' => 'class_id',
            'default_value' => '',
            'field_type' => 'int',
            'field_length' => 11,
            'obj_location' => 1,
            'obj_type' => '_select',
            'obj_valid' => 'require|number',
            'obj_options' => '{"datatype":"*","empty-option":"|请选择栏目分类","items-data":"D:cms.Class:getList:' . $tableName . '","items-key":"id","items-name":"name"}',
            'obj_status' => 1,
            'show_order' => 1
        ], [
            'table_name' => $tableName,
            'label_name' => '标题',
            'field_name' => 'title',
            'default_value' => '',
            'field_type' => 'varchar',
            'field_length' => 255,
            'obj_location' => 1,
            'obj_type' => '_text',
            'obj_valid' => 'require',
            'obj_options' => '{"datatype":"*","placeholder":"请输入标题"}',
            'obj_status' => 1,
            'show_order' => 2
        ], [
            'table_name' => $tableName,
            'label_name' => '跳转URL',
            'field_name' => 'jump',
            'default_value' => '',
            'field_type' => 'varchar',
            'field_length' => 255,
            'obj_location' => 2,
            'obj_type' => '_text',
            'obj_valid' => '',
            'obj_options' => '',
            'obj_status' => 1,
            'show_order' => 100
        ]
    ];
    $fieldModel->saveAll($dataList);
  }

}